package com.buaa.util;

import java.sql.Connection;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

public class HibernateUtils {

	private static SessionFactory sf;

	static {
		Configuration cfg = new Configuration().configure();
		ServiceRegistry sr = new StandardServiceRegistryBuilder().applySettings(cfg.getProperties()).build();
		sf = cfg.buildSessionFactory(sr);
		Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
			@Override
			public void run() {
				System.out.println("释放资源");
				sf.close();
			}
		}));
	}

	/**
	 * 新建一个Session
	 * 
	 * @return
	 */
	public static Session openSession() {
		return sf.openSession();
	}

	/**
	 * 获取当前Session
	 * 
	 * @return
	 */
	public static Session getCurrentSession() {
		return sf.getCurrentSession() == null ? openSession() : sf.getCurrentSession();
	}

	/**
	 * 通过hql语句获取对象集合
	 * 
	 * @param hql
	 * @param args
	 * @return
	 */
	@SuppressWarnings({ "rawtypes" })
	public static List findByHQL(String hql, Object[] args) {
		Session session = sf.openSession();
		Query query = session.createQuery(hql);
		constructorQuery(query, args);
		List list = query.list();
		if (validateIfNull(list))
			return null;
		releaseSession(session);
		return list;
	}

	/**
	 * 通过sql语句获取对象集合
	 * 
	 * @param sql
	 * @param args
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<Object> findBySQL(String sql, Object[] args) {
		Session session = sf.openSession();
		SQLQuery sqlQuery = session.createSQLQuery(sql);
		constructorQuery(sqlQuery, args);
		List<Object> list = sqlQuery.list();
		if (validateIfNull(list))
			return null;
		releaseSession(session);
		return list;
	}

	/**
	 * 构造带参数的Query
	 * 
	 * @param query
	 * @param args 参数数组
	 * @return
	 */
	private static Query constructorQuery(Query query, Object[] args) {
		if (args == null || args.length == 0)
			return query;
		else {
			for (int i = 0; i < args.length; i++) {
				query.setParameter(i, args[i]);
			}
		}
		return query;
	}

	/**
	 * 验证list是否为空
	 * 如果返回值为true，表示list为空；返回值为false，表示list不为空
	 * 
	 * @param list
	 * @return
	 */
	private static boolean validateIfNull(List<?> list) {
		if (list.size() == 0)
			return true;
		return false;
	}

	/**
	 * 释放session
	 * 
	 * @param session
	 */
	private static void releaseSession(Session session) {
		Connection conn = session.close();
		if (conn != null)
			throw new RuntimeException("attention,session close error.....");
	}

}
